use leptos::prelude::*;
use leptos::task::spawn_local;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LoginType {
    Account,
    Email,
    Phone,
}

impl LoginType {
    fn placeholder(self) -> &'static str {
        match self {
            LoginType::Account | LoginType::Email | LoginType::Phone => "请输入账号/邮箱/手机号",
        }
    }

    fn detect_type(credential: &str) -> Self {
        if credential.contains('@') {
            LoginType::Email
        } else if credential.chars().all(char::is_numeric) && credential.len() == 11 {
            LoginType::Phone
        } else {
            LoginType::Account
        }
    }
}

/// Login Box Component
/// A modern, responsive login form with dark theme
#[component]
#[must_use]
pub fn UiLogin(
    #[prop(optional)] class: Option<String>,
    #[prop(optional)] on_submit: Option<Callback<(LoginType, String, String)>>,
) -> impl IntoView {
    let (credential, set_credential) = signal(String::new());
    let (password, set_password) = signal(String::new());
    let (error, set_error) = signal(Option::<String>::None);
    let (loading, set_loading) = signal(false);

    let handle_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();

        let credential_val = credential.get();
        let password_val = password.get();

        // Basic validation
        if credential_val.is_empty() || password_val.is_empty() {
            set_error.set(Some("账号和密码不能为空".to_string()));
            return;
        }

        // Detect login type based on credential
        let detected_type = LoginType::detect_type(&credential_val);

        // Type-specific validation
        match detected_type {
            LoginType::Email => {
                if !credential_val.contains('@') || !credential_val.contains('.') {
                    set_error.set(Some("请输入有效的邮箱地址".to_string()));
                    return;
                }
            }
            LoginType::Phone => {
                if !credential_val.chars().all(char::is_numeric) || credential_val.len() != 11 {
                    set_error.set(Some("请输入有效的11位手机号".to_string()));
                    return;
                }
            }
            LoginType::Account => {
                if credential_val.len() < 3 {
                    set_error.set(Some("账号长度至少3个字符".to_string()));
                    return;
                }
            }
        }

        set_error.set(None);
        set_loading.set(true);

        // Call the callback if provided
        if let Some(cb) = on_submit {
            cb.run((detected_type, credential_val, password_val));
        }

        // Reset loading state after a short delay (simulating async)
        spawn_local(async move {
            gloo_timers::future::TimeoutFuture::new(1_000).await;
            set_loading.set(false);
        });
    };

    let base = "w-full";
    let class = class.map_or_else(|| base.to_string(), |c| format!("{base} {c}"));

    view! {
        <div class=class>
            // 装饰性元素
            <div class="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none">
                <div class="absolute -top-1/2 -left-1/2 w-full h-full bg-gradient-to-r from-blue-400/10 to-indigo-600/10 rounded-full blur-3xl"></div>
                <div class="absolute -bottom-1/2 -right-1/2 w-full h-full bg-gradient-to-r from-cyan-400/10 to-blue-500/10 rounded-full blur-3xl"></div>
            </div>

            <div class="text-center mb-8 relative z-10">
                <div class="mx-auto w-12 h-12 rounded-full bg-blue-500/20 flex items-center justify-center mb-4 backdrop-blur-sm border border-white/20">
                    <svg class="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                    </svg>
                </div>
                <h2 class="text-3xl font-bold text-white mb-3">
                    "R² Meta-Orchestrated"
                </h2>
                <p class="text-base text-gray-300">
                    "请输入您的账号信息"
                </p>
            </div>

            // Error message
            {move || error.get().map(|err| view! {
                <div class="mb-6 p-4 rounded-lg bg-red-900/50 border border-red-700/50 backdrop-blur-sm flex items-start">
                    <svg class="w-5 h-5 text-red-300 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    <p class="text-red-200">{err}</p>
                </div>
            })}

            // Form
            <form on:submit=handle_submit class="space-y-6 relative z-10">
                // Credential field (Account/Email/Phone)
                <div>
                    <label
                        for="credential"
                        class="block text-base font-medium text-gray-300 mb-2"
                    >
                        "账号"
                    </label>
                    <div class="relative">
                        <input
                            type="text"
                            id="credential"
                            class="w-full px-4 py-3 rounded-md border border-gray-600/50
                                   bg-black/20 text-white placeholder-gray-400
                                   focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                                   transition duration-200 backdrop-blur-sm"
                            placeholder=move || LoginType::Account.placeholder()
                            prop:value=move || credential.get()
                            on:input=move |ev| {
                                set_credential.set(event_target_value(&ev));
                                set_error.set(None);
                            }
                            disabled=move || loading.get()
                        />
                    </div>
                </div>

                // Password field
                <div>
                    <label
                        for="password"
                        class="block text-base font-medium text-gray-300 mb-2"
                    >
                        "密码"
                    </label>
                    <div class="relative">
                        <input
                            type="password"
                            id="password"
                            class="w-full px-4 py-3 rounded-md border border-gray-600/50
                                   bg-black/20 text-white placeholder-gray-400
                                   focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                                   transition duration-200 backdrop-blur-sm"
                            placeholder="请输入密码"
                            prop:value=move || password.get()
                            on:input=move |ev| {
                                set_password.set(event_target_value(&ev));
                                set_error.set(None);
                            }
                            disabled=move || loading.get()
                        />
                    </div>
                </div>

                // Remember me & Forgot password
                <div class="flex items-center justify-between">
                    <label class="flex items-center cursor-pointer">
                        <input
                            type="checkbox"
                            class="w-5 h-5 rounded border-gray-600 text-blue-500 bg-black/20
                                   focus:ring-blue-500 focus:ring-offset-0 backdrop-blur-sm"
                        />
                        <span class="ml-2 text-gray-300">
                            "记住我"
                        </span>
                    </label>
                    <a
                        href="#"
                        class="text-blue-400 hover:text-blue-300 transition"
                    >
                        "忘记密码？"
                    </a>
                </div>

                // Submit button
                <button
                    type="submit"
                    class="w-full py-4 px-4 rounded-md font-medium text-white text-base
                           bg-gradient-to-r from-blue-600 to-indigo-700
                           hover:from-blue-700 hover:to-indigo-800
                           focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
                           disabled:opacity-50 disabled:cursor-not-allowed
                           transition duration-300 shadow-lg shadow-blue-500/30 flex items-center justify-center
                           transform hover:scale-[1.02] active:scale-[0.98]"
                    disabled=move || loading.get()
                >
                    {move || {
                        if loading.get() {
                            view! {
                                <span class="flex items-center">
                                    <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                    "登录中..."
                                </span>
                            }.into_view()
                        } else {
                            view! {
                                <span class="flex items-center">
                                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
                                    </svg>
                                    "登录"
                                </span>
                            }.into_view()
                        }
                    }}
                </button>
            </form>

            // Footer
            <div class="mt-8 text-center relative z-10">
                <p class="text-gray-400">
                    "还没有账户？ "
                    <a
                        href="#"
                        class="text-blue-400 hover:text-blue-300 font-medium transition"
                    >
                        "立即注册"
                    </a>
                </p>
            </div>
        </div>
    }
}
